<?php
namespace App\Http\Controllers\Api\v1\Article;

use App\Http\Controllers\Api\BaseController;
use App\Models\Api\User;
use App\Models\Article;
use App\Models\Comment;
use App\Models\Like;
use DB;
use Illuminate\Http\Request;

// 用户中心
class CommentController extends BaseController
{

    // 增加评论 api
    public function store(Request $request)
    {
        $article_id = $request->input('id'); //文章id
        $user_id    = $request->uid; //评论id
        $content    = $request->input('content'); //回复内容
        $p_id       = $request->input('pid', 0); // 回复楼层id
        $r_id       = intval($request->input('rid', 0)); //回复用户id

        $comment = DB::table('comments')
            ->where(['article_id' => $article_id, 'uid' => $request->uid, 'content' => $content])->first();

        if (!empty($comment)) {
            return show(0, '不要重复评论', []);
        }

       $result =contentCensor($content);

       if ($result['status'] === 2) {
           // \Log::info('占卜错误:' . $validate->getError());
            return show(config('code.error'), $result['msg']);
        }
        $data = [
            'article_id' => $article_id,
            'uid'    => $user_id,
            'content'    => $content,
            'p_id'       => $p_id,
            'to_uid'     => $r_id,
        ];
        $validate = new \App\Tools\Validates\Comment();

        if (!$validate->scene('add')->check($data)) {
            return show(config('code.error'), (string) $validate->getError());
        }

        $comment    = (new User())->comments()->create($data);
        $article = Article::find($comment['article_id']);
        $article->increment('count_comment', 1);
        $comment->increment('count_comment', 1);
        $comment = $comment->where(['id'=>$comment['id'],'article_id'=>$comment['article_id'],'uid'=>$request->uid])->with('user','rUser')->first();
          if($comment['to_uid'] !=0 && $comment['to_uid'] !=NULL){
            $messageData = [
                    'uid' => $comment['to_uid'],
                    'r_uid'=>$comment['uid'],
                    'type' => 3,
                    'cid' => 5, //星文分类cid
                    'title' => '你的评论有回复',
                    'content' => $comment['content'],
                    'link' =>'article_details?id='.$article_id,
                    'target' => "local",
                ];
            //添加消息
         (new MessageCenter())->pushMessage($messageData);
         (new Push())->pushSpecial($comment['rUser']['regid'], '你的评论有回复,点击查看详情！', [
                        'action' => 'article_details',
                        'id' => $article_id,
                    ]);
        }
         \Log::info('推送成功：' . $comment);

        if ($comment) {
            return show(config('code.success'), 'Reply success.', $comment);
        } else {
            return show(config('code.error'), '回复失败,请稍后再试');
        }

    }

    // 删除评论 api
    public function destroy(Request $request, Comment $comment)
    {
        if (!$request->isMethod('post')) {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $id   = $request->input('id');
        $article_id   = $request->input('a_id');
        $article = Article::where(['id'=>$article_id])->first();
        $article->decrement('count_comment', 1);
        $data = $comment->destroy($id);
        if ($data) {
            return show(config('code.success'), '删除成功', $data);
        } else {
            return show(config('code.error'), '删除失败');
        }
    }

    // 我的评论
     public function comment_me(Request $request)
    {
        $page     = intval($request->input('page'));
        $user     = User::select('id', 'nickname', 'avatar')->where('id', $request->uid)->first();
        $articles = $user->likeComments(['uid'=>$request->uid])->paginate($page)->toArray();

        return show(200, '我评论的文章', $articles);
    }
    // 回复我的评论
    public function reply_me(Request $request)
    {
        $page     = intval($request->input('page', 10));
        $user     = User::select('id', 'nickname', 'avatar')->where('id', $request->uid)->first();
        $Comments = $user->rMyComments('p')->with('user','rUser','childs','childs.user', 'childs.rUser')->paginate(10)->toArray();

        return show(200, '回复我的评论', $Comments);
    }
    // 点赞评论
    public function like(Request $request)
    {
        $id = intval($request->get('id'));
        if (empty($id)) {
            return show(config('code.error'), '评论id不能为空', [], 403);
        }
        $comment = Comment::findOrFail($id);
        $res     = $comment->isLike(true, $request->uid);
        if ($res == 1) {
            $like = $comment->likes()->where(['uid' => $request->uid])->delete();
            $comment->decrement('count_like', 1);
            $img       = 'images/111_03.jpg';
            $zanstatus = '-1';
            $message   = 'Good cancel success.';
        } else {
            $comment->likes()->create(['uid' => $request->uid]);
            $comment->increment('count_like', 1);
            $img       = 'images/111_03-on.jpg';
            $zanstatus = '1';
            $message   = 'Good success.';
        }

        $data = ['count' => $comment->count_like, 'img' => $img, 'zanstatus' => $zanstatus];
        return show(200, $message, $data);
    }

    /**
     * 文章评论拉取
     */
    public function lists(Request $request)
    {

        $id = $request->input('id');
        if (empty($id)) {
            return show(config('code.error'), '文章id不能为空', [], 403);
        }
        $list = Article::with(['user' => function ($query) {
            $query->select('id', 'nickname', 'avatar');
        }])
            ->where('status', 1)
            ->OrderBy('created_at', 'desc')
            ->find($id);
      if (!$list) {
        return show(config('code.error'), '文章不存在', [], 404);
        }
        $data = $list->comments('p')->with([
             'user' => function ($query) {
                   $query->select('user.id','user.uen','user.tel','user.uc_id','user.nickname','user.sex','user.avatar','user.status','user.has_self_recode','user.forbidden','user.regid', 'recode_astro.sun', 'recode_astro.moon','recode_astro.asc') // 数据字段
                    ->join('recode', 'user.id', '=', 'recode.uid')
                    ->join('recode_astro', 'recode.id', '=', 'recode_astro.rid')
                    ->where('recode.isself','1'); //输出 child comments信息
                },
            'childs' => function ($query) {
                $query->with('user','rUser'); // Load user data for direct child comments
            }
        ])->withCount('childs')->paginate(15);
    if ($data->isEmpty()) {
        // Handle the case where there are no comments
        return show(config('code.success'), '没有更多评论数据',$data);
      }
         // 处理点赞信息
    if ($request->uid) {
        foreach ($data as &$comment) {
           // var_dump($comment);die;
            $comment['is_liked'] = $comment->isLike(true, $request->uid);

            foreach ($comment['childs'] as &$childComment) {
                $childComment['is_liked'] = $childComment->isLike(true, $request->uid);
            }
        }
    }
       $commentlist =  $data->toArray();
       $totalChildCount = 0; // Initialize the total child count
        foreach ($commentlist['data'] as $comment) {
            $totalChildCount += $comment['childs_count'];
        }

        $commentlist['total'] = $commentlist['total'] + $totalChildCount;
        return show(200, '评论拉取成功', $commentlist);
    }
    /**
     * 过滤敏感词汇
     * @param $content
     * @return bool
     */
    protected function filter_words($content)
    {
        $words  = config('words.words');
        $status = false;
        foreach ($words as $w) {
            if (strpos($content, $w) !== false) {
                $status = true;
            }
        }

        if (in_array($content, $words)) {
            $status = true;
        }

        return $status;
    }
}
